package base

import (
	"context"
	"fmt"
	"github.com/go-resty/resty/v2"
	"github.com/pkg/errors"
)

type HttpClient struct {
	baseURL string
	client  *resty.Client
}

type BaseRespData struct {
	Code    int         `json:"code"`
	Message interface{} `json:"message"`
	Msg     interface{} `json:"msg"`
	Data    interface{} `json:"data"`
}

func NewHttpClient(baseURL string) *HttpClient {
	client := resty.New().
		SetHeader("Content-Type", "application/json")

	return &HttpClient{
		baseURL: baseURL,
		client:  client,
	}
}

func (client *HttpClient) DoPostRequest(ctx context.Context, path string, req, rsp interface{}, retMap interface{}) error {
	ret := &BaseRespData{Data: rsp}
	rspItem := client.client.NewRequest()
	if retMap != nil {
		rspItem.SetResult(retMap)
	} else {
		rspItem.SetResult(ret)
	}
	getResp, err := rspItem.SetBody(req).Post(path)
	if err != nil {
		return err
	}

	if !getResp.IsSuccess() {
		return errors.New(fmt.Sprintf("check getResp.IsSuccess() failed, code is %v", getResp.StatusCode()))
	}
	if rsp != nil {
		ret = getResp.Result().(*BaseRespData)
		if ret.Code != 0 {
			return fmt.Errorf("do request at: %s, code: %v, msg: %v", path, ret.Code, ret.Msg)
		}
	}
	return nil
}

func (client *HttpClient) DoGetRequest(ctx context.Context, path string, rsp interface{}, retMap interface{}) error {
	ret := &BaseRespData{Data: rsp}
	rspItem := client.client.NewRequest()
	if retMap != nil {
		rspItem.SetResult(retMap)
	} else {
		rspItem.SetResult(ret)
	}
	getResp, err := rspItem.Get(path)
	if err != nil {
		return err
	}

	if !getResp.IsSuccess() {
		return errors.New("check getResp.IsSuccess() failed")
	}

	if rsp != nil {
		ret = getResp.Result().(*BaseRespData)
		if ret.Code != 0 {
			return fmt.Errorf("do request at: %s, code: %v, msg: %v", path, ret.Code, ret.Msg)
		}
	}
	return nil
}
